#include "StdAfx.h"
#include "ListElementUI.h"

CListElementUI::CListElementUI(void):
m_iIndex(-1),
m_pOwner(NULL), 
m_bSelected(false)
{
}

CListElementUI::~CListElementUI(void)
{
}

UINT CListElementUI::GetControlFlags() const
{
	return UIFLAG_WANTRETURN;
}

LPVOID CListElementUI::GetInterface(LPCTSTR pstrName)
{
	if( _tcscmp(pstrName, _T("ListItem")) == 0 ) return static_cast<IListItemUI*>(this);
	return CControlUI::GetInterface(pstrName);
}

void CListElementUI::SetOwner(CControlUI* pOwner)
{
	m_pOwner = static_cast<IListOwnerUI*>(pOwner->GetInterface(_T("ListOwner")));
}

int CListElementUI::GetIndex() const
{
	return m_iIndex;
}

void CListElementUI::SetIndex(int iIndex)
{
	m_iIndex = iIndex;
}

bool CListElementUI::Activate()
{
	if( !CControlUI::Activate() ) return false;
	if( m_pManager != NULL ) m_pManager->SendNotify(this, _T("itemactivate"));
	return true;
}

bool CListElementUI::IsSelected() const
{
	return m_bSelected;
}

bool CListElementUI::Select(bool bSelect)
{
	if( !IsEnabled() ) return false;
	if( bSelect == m_bSelected ) return true;
	m_bSelected = bSelect;
	if( bSelect && m_pOwner != NULL ) m_pOwner->SelectItem(m_iIndex);
	Invalidate();
	return true;
}

bool CListElementUI::IsExpanded() const
{
	return false;
}

bool CListElementUI::Expand(bool /*bExpand = true*/)
{
	return false;
}

void CListElementUI::Event(TEventUI& event)
{
	if( event.Type == UIEVENT_DBLCLICK && IsEnabled() )
	{
		Activate();
		Invalidate();
		return;
	}
	if( event.Type == UIEVENT_KEYDOWN && IsEnabled() )
	{
		if( event.chKey == VK_RETURN ) {
			Activate();
			Invalidate();
			return;
		}
	}
	// An important twist: The list-item will send the event not to its immediate
	// parent but to the "attached" list. A list may actually embed several components
	// in its path to the item, but key-presses etc. needs to go to the actual list.
	if( m_pOwner != NULL ) m_pOwner->Event(event); else CControlUI::Event(event);
}

void CListElementUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
	if( _tcscmp(pstrName, _T("selected")) == 0 ) Select();
	else CControlUI::SetAttribute(pstrName, pstrValue);
}